package com.sdk.es.http.exception;

import cn.hutool.json.JSONUtil;
import com.sdk.es.sdk.entity.common.EsResult;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.elasticsearch.NoSuchIndexException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Map;

/**
 * @author: eshore
 * @since: 2021/5/28 17:20
 * @DESCRIPTION:
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 自定义业务异常
     * @author limaosheng
     * @create 15:17 2022/8/11
     * @param e
     */
    @ExceptionHandler(SaasException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public EsResult eventsException(SaasException e) {
        log.error("业务异常->错误码:{},错误信息:{}", e.getCode(),e.getMessage());
        return EsResult.fail(e.getCode(),e.getMessage());
    }

    @ExceptionHandler(NoSuchIndexException.class)
    public EsResult noSuchIndexException(Exception e, HttpServletRequest request) {
        log.error("全局异常拦截，排障业务侧异常:{}, 请求参数：{}", e.getMessage(), this.jsonParams(request), e);
        if(e.getMessage() != null && e.getMessage().length() < 100){
            return EsResult.fail(SaasErrorEnum.NO_SUCH_INDEX.getKey(),e.getMessage());
        }
        return EsResult.fail(SaasErrorEnum.NO_SUCH_INDEX.getKey(),SaasErrorEnum.NO_SUCH_INDEX.getDesc());
    }

    @ExceptionHandler(Exception.class)
    public EsResult exception(Exception e, HttpServletRequest request) {
        log.error("全局异常拦截，排障业务侧异常:{}, 请求参数：{}", e.getMessage(), this.jsonParams(request), e);
        return EsResult.fail(SaasErrorEnum.INTERNAL_SERVER_ERROR.getKey(),SaasErrorEnum.INTERNAL_SERVER_ERROR.getDesc());
    }

    private String jsonParams(HttpServletRequest request) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        return JSONUtil.toJsonStr(parameterMap);
    }
}
